/************************************************************************/
/* 
*/
/************************************************************************/

#include "glwidget.h"
#include <iostream>
#include <cstring>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>


GLWidget::GLWidget(EGLNativeDisplayType nativeDpy, EGLNativeWindowType nativeWindow)
{
	static const EGLint context_attribs[] = 
	{
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};

	const char *extensions;

	EGLint config_attribs[] = {
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RED_SIZE, 1,
		EGL_GREEN_SIZE, 1,
		EGL_BLUE_SIZE, 1,
		EGL_ALPHA_SIZE, 1,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_NONE
	};

	EGLint major, minor, n, count, i, size;
	EGLConfig *configs;
	EGLBoolean ret;

	egldpy = eglGetDisplay(nativeDpy);

	ret = eglInitialize(egldpy, &major, &minor);
	ret = eglBindAPI(EGL_OPENGL_ES_API);

	eglGetConfigs(egldpy, NULL, 0, &count);

	configs = (EGLConfig *)calloc(count, sizeof *configs);

	ret = eglChooseConfig(egldpy, config_attribs, configs, count, &n);

	for (i = 0; i < n; i++) 
	{
		eglGetConfigAttrib( egldpy, configs[i], EGL_BUFFER_SIZE, &size );

		if (32 == size) 
		{
			eglconf = configs[i];
			break;
		}
	}

	free(configs);
	if (eglconf == NULL) 
	{
		printf("did not find config with buffer size %d\n", 32);
		exit(EXIT_FAILURE);
	}

	eglctx = eglCreateContext(egldpy, eglconf, EGL_NO_CONTEXT, context_attribs);

	egl_surface = eglCreateWindowSurface(egldpy, eglconf, nativeWindow, NULL);
	ret = eglMakeCurrent(egldpy, egl_surface, egl_surface, eglctx);
}

GLWidget::~GLWidget(void)
{
	eglMakeCurrent( egldpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
	eglDestroySurface( egldpy, egl_surface );
	eglTerminate( egldpy );
	eglReleaseThread();
}

GLuint GLWidget::create_shader( const char *source, GLenum shader_type )
{
	GLuint shader;
	GLint status;

	shader = glCreateShader(shader_type);
	assert(shader != 0);

	glShaderSource(shader, 1, (const char **) &source, NULL);
	glCompileShader(shader);
	glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

	if (!status) 
	{
		char log[1000];
		GLsizei len;
		glGetShaderInfoLog(shader, 1000, &len, log);
		printf( "Error: compiling %s: %*s\n", shader_type == GL_VERTEX_SHADER ? "vertex" : "fragment", len, log );
		exit(1);
	}

	return shader;
}

std::string GLWidget::module_path()
{
	char modulepath[1024];
	ssize_t len;
	if ( (len = readlink("/proc/self/exe", modulepath, sizeof(modulepath)-1)) != -1 ) {
		modulepath[len] = '\0';		
	}

	std::string s1(modulepath);
	int pos = s1.rfind('/');
	if( pos != s1.npos ) {
		std::string s2( modulepath, pos);
		return s2;
	}

	return std::string();
}

